<template>
  <div class="cont" @click="close">
    <canvas ref="c" style="display: none"> </canvas>
    <vue-qr
      ref="qrcode"
      style="display: none"
      :logoSrc="logo"
      text="Hello world!"
      :size="200"
    ></vue-qr>
    <img :src="content" alt="" />
  </div>
</template>

<script>
import goodImg from "@/assets/no.png";
import logo from "@/assets/logo.png";
import VueQr from "vue-qr";
export default {
  data() {
    return {
      goodImg,
      logo,
      content: "",
      loaded: false,
    };
  },
  components: {
    VueQr,
  },
  props: ["goodInfo"],
  methods: {
    close() {
      this.$emit("closeMod2");
      this.$emit('closeLoad')
    },
    createCanvas() {
      let c = this.$refs.c;
      let ctx = c.getContext("2d");
      c.height = window.devicePixelRatio * screen.availHeight;
      c.width = window.devicePixelRatio * screen.availWidth;

      // 设置画布背景颜色
      var imgData = ctx.createImageData(c.width, c.height);
      for (var i = 0; i < imgData.data.length; i += 4) {
        imgData.data[i + 0] = 255;
        imgData.data[i + 1] = 255;
        imgData.data[i + 2] = 255;
        imgData.data[i + 3] = 255;
      }
      // putImageData讲图像数据放回到画布上
      ctx.putImageData(imgData, 0, 0);
      // 创建商品详情
      ctx.font = "30px serif";
      ctx.fillStyle = "red";
      ctx.fillText("￥" + this.goodInfo.price, 50, c.height / 2 + 50);

      ctx.fillStyle = "#666";
      ctx.fillText(this.goodInfo.name.slice(0, 20), 50, c.height / 2 + 120);
      ctx.fillText(
        this.goodInfo.name.slice(20, 40) + "...",
        50,
        c.height / 2 + 180
      );

      // 创建商品图片
      let img = new Image(); 
      img.crossOrigin = '';
      img.src = this.goodImg;
      // 添加二维码
      let qrcode = this.$refs.qrcode.imgUrl;
      let qrimg = new Image();
      qrimg.src = qrcode;
      img.onload = function () {
        ctx.drawImage(img, 25, 0, c.width - 50, c.height / 2);
        this.loaded = true;
      };

      qrimg.onload = () => {
        ctx.drawImage(qrimg, c.width/2-100, c.height/2+250, 200, 200);
      };
      setTimeout(() => {
        this.content = c.toDataURL();
      this.$emit('closeLoad')

      }, 1000);
    },
    
  },
  mounted() {

    setTimeout(() => {
      this.createCanvas();
    }, 2000);
  },
};
</script>

<style lang="less" scoped>
.cont {
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  position: absolute;
  top: 0;
  left: 0;
  z-index: 999;
  img {
    width: 80%;
    margin: 10%;
  }
}
</style>